package com.googlecode.imule.discovery;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.NoSuchElementException;

import com.apple.dnssd.DNSSDException;

/**
 * Maintain the contact information regarding a individual service.
 * 
 * Store the logical information (i.e service name, domain...).
 * 
 * @author Neil Cowzer
 */
public class ContactList implements Iterable<Contact>{

	/* the list of available contacts that we know of */
	private Hashtable<String, Contact> contactList;
	
	/**
	 * Create a new empty ContactList
	 */
	public ContactList() {
		contactList = new Hashtable<String, Contact>();
	}


	/**
	 * Add a Contact to the list of known services.
	 * 
	 * @param serviceName
	 * @param domain
	 * @param regType
	 * @param ifIndex
	 */
	public void addContact(String serviceName, String domain, String regType, int ifIndex){
		try {
			Contact contact = new Contact(serviceName, domain, regType, ifIndex);
			contactList.put(serviceName, contact);	// add to the list
		} catch (DNSSDException e) {
			System.out.println("Failed to add: "+ serviceName);
			e.printStackTrace();
		}
	}
	
	/**
	 * Remove a Contact from the list of registered Contacts.
	 * 
	 * @param serviceName the name of the contact/service
	 */
	public void removeContact(String serviceName){
		contactList.remove(serviceName);
	}
	
	/**
	 * Retrieve a specific contacts information.
	 * 
	 * @param serviceName
	 * @return
	 */
	public Contact getContact(String serviceName){
		return contactList.get(serviceName);
	}
	
	/**
	 * Retrieve an iterator over this class
	 */
	public Iterator<Contact> iterator() {
		return new Iterator<Contact>() {
		
			Contact contact;
			Iterator<String> keys;
			
			public void remove() {
				throw new UnsupportedOperationException();	// too much effort to implement
			}
		
			public Contact next() {
				if (contact == null) throw new NoSuchElementException();
				return contact;
			}
		
			public boolean hasNext() {
				if (keys == null)
					keys = contactList.keySet().iterator();
				
				try {
					contact = contactList.get(keys.next());	// update position of contact
				} catch (NoSuchElementException e){
					return false;
				} 
				
				return true;
			}
		
		};
	}
}
